import { Navigate, redirect } from "react-router-dom";
import React, { Suspense } from "react";
import KeepAlive from "react-activation";
import Layout from "../layout/index.jsx";
import Login from "../pages/Login/index.jsx";

const Person = React.lazy(() => import("../pages/Person/index.jsx"));
const Goods = React.lazy(() => import("../pages/Goods/index.jsx"));
const ErrorPage = React.lazy(() => import("../pages/ErrorPage/index.jsx"));
const Setting = React.lazy(() => import("../pages/Setting/index.jsx"));
const HomePage = React.lazy(() => import("../pages/HomePage/index.jsx"));

const routeMap = {
  AddRouteTest: React.lazy(() => import("../pages/AddRouteTest/index.jsx")),
};
const Loading = () => {
  return <div>Loading...</div>;
};
// 🌈 封装路由守卫逻辑
const checkAuth = () => {
  return localStorage.getItem("token"); // 替换为你的登录态校验逻辑
};

// 🔒 路由守卫高阶函数   用loader写路由守卫
const protectedLoader = async () => {
  if (!checkAuth()) {
    return redirect("/login"); // 未登录跳转到登录页
  }
  return null;
};
//注意路由缓存 KeepAlive  和懒加载的Suspense的包裹顺序
const staticRoutes = [
  {
    path: "/",
    element: <Navigate to={"/login"} replace />, //重定向to:前往路由  replace:是否替换历史堆栈中的当前条目  false可后退前一个路由
  },
  {
    path: "/login",
    title: "登录页",
    element: <Login />,
  },
  {
    path: "/",
    title: "内容区",
    element: <Layout />,
    children: [
      {
        path: "/home",
        title: "首页",
        name: "home",
        element: (
          <KeepAlive id={"/home"} name={"/home"} cacheKey={"/home"}>
            <Suspense fallback={<Loading />}>
              <HomePage />
            </Suspense>
          </KeepAlive>
        ),
      },
      {
        path: "/system",
        title: "系统管理",
        name: "system",
        children: [
          {
            path: "/system/person",
            title: "用户管理",
            name: "person",
            children: [
              {
                path: "/system/person/user",
                title: "用户姓名",
                name: "user",
                element: (
                  <KeepAlive
                    name={"/system/person/user"}
                    id={"/system/person/user"}
                    cacheKey={"/system/person/user"}
                  >
                    <Suspense fallback={<Loading />}>
                      <Person />
                    </Suspense>
                  </KeepAlive>
                ),
              },
            ],
          },
          {
            path: "/system/goods",
            title: "货物管理",
            name: "goods",
            element: (
              <KeepAlive
                id={"/system/goods"}
                name={"/system/goods"}
                cacheKey={"/system/goods"}
              >
                <Suspense fallback={<Loading />}>
                  <Goods />
                </Suspense>
              </KeepAlive>
            ),
          },
        ],
      },
      {
        path: "/setting",
        title: "设置",
        element: (
          <KeepAlive id={"/setting"} name={"/setting"} cacheKey={"/setting"}>
            <Suspense fallback={<Loading />}>
              <Setting />
            </Suspense>
          </KeepAlive>
        ),
      },
    ],
  },
  {
    path: "/404page",
    title: "无权限",
    element: <Goods />,
    loader: protectedLoader,
  },
  {
    path: "*",
    element: <ErrorPage />,
  },
];

export const disposeJavaRoute = (list) => {
  function getData(data) {
    let arr = [];
    if (!Array.isArray(data) || !data.length) return arr;
    data.forEach((item) => {
      let obj = {
        path: item.path,
        title: item.title,
        element: (
          <KeepAlive id={item.path} name={item.path} cacheKey={item.path}>
            <Suspense fallback={<Loading />}>
              {React.createElement(routeMap[item.element])}
            </Suspense>
          </KeepAlive>
        ),
      };
      if (item.children && item.children.length) {
        obj.children = disposeJavaRoute(item.children);
      }
      arr.push(obj);
    });
    return arr;
  }
  const result = getData(list);
  if (result.length) {
    result.forEach((item) => {
      if (
        !staticRoutes[2].children.some((element) => element.path === item.path)
      )
        staticRoutes[2].children.push(item);
    });
  }
  return staticRoutes;
};

export const routes = staticRoutes;

// createBrowserRouter：history路由（推荐）
//
// createHashRouter：哈希路由（不推荐）
//
// createMemoryRouter：有自己的一套路由记忆栈，用于生产开发工具、无浏览器环境使用
//
// createStaticRouter：用于服务器
